
package cn.elead.chaos.framework.config;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.fasterxml.jackson.databind.ObjectMapper;

import cn.elead.chaos.framework.properties.ChaosProperties;
import cn.elead.chaos.framework.util.JacksonUtils;
import cn.elead.chaos.framework.web.enums.IEnumConverterFactory;
import cn.elead.chaos.framework.web.global.exception.ChaosHandlerExceptionResolver;
import cn.elead.chaos.framework.web.validator.ValidatorCollectionImpl;
import lombok.extern.slf4j.Slf4j;

/**
 * WEB 配置
 *
 * @author luopeng
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(ChaosProperties.class)
public class WebAutoConfiguration implements WebMvcConfigurer {

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private ChaosHandlerExceptionResolver epomHandlerExceptionResolver;

	@Override
	public Validator getValidator() {
		return new SpringValidatorAdapter(new ValidatorCollectionImpl());
	}

	/**
	 * 枚举转换
	 */
	@Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addConverterFactory(new IEnumConverterFactory());
		log.info("开启枚举转换支持");
	}

	/**
	 * json序列化
	 */
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		converters.forEach(JacksonUtils.wrapperObjectMapper());
	}

	@Override
	public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
		converters.set(0, new MappingJackson2HttpMessageConverter(objectMapper));
	}

	/**
	 * 全局异常
	 */
	@Override
	public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
		exceptionResolvers.add(epomHandlerExceptionResolver);
		log.info("开启全局异常支持");
	}
}
